package cn.sfrog.project.biz.admin.service.impl;

import cn.hutool.json.JSONUtil;
import cn.sfrog.common.core.domain.entity.SysUser;
import cn.sfrog.common.exception.ApiException;
import cn.sfrog.common.utils.DateUtils;
import cn.sfrog.common.utils.SecurityUtils;
import cn.sfrog.common.utils.StringUtils;
import cn.sfrog.project.biz.admin.domain.BizServiceOrder;
import cn.sfrog.project.biz.admin.domain.BizServiceOrderEvaluation;
import cn.sfrog.project.biz.admin.domain.vo.BizServiceOrderEvaluationFormVO;
import cn.sfrog.project.biz.admin.domain.vo.BizServiceOrderEvaluationQueryVO;
import cn.sfrog.project.biz.admin.domain.vo.BizServiceOrderEvaluationVO;
import cn.sfrog.project.biz.admin.mapper.BizServiceOrderEvaluationMapper;
import cn.sfrog.project.biz.admin.service.IBizServiceOrderEvaluationService;
import cn.sfrog.project.biz.web.vo.order.AppOrderEvaluationVO;
import cn.sfrog.project.biz.web.vo.order.AppServiceOrderEvaluationFormVO;
import cn.sfrog.system.domain.vo.BizAuditVO;
import cn.sfrog.system.domain.vo.BizStatusChangeVO;
import cn.sfrog.system.mapper.SysUserMapper;
import cn.sfrog.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 订单评价Service业务层处理
 */
@Service
public class BizServiceOrderEvaluationServiceImpl extends ServiceImpl<BizServiceOrderEvaluationMapper, BizServiceOrderEvaluation> implements IBizServiceOrderEvaluationService {
    @Resource
    private BizServiceOrderEvaluationMapper bizServiceOrderEvaluationMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 查询订单评价
     *
     * @param id 订单评价主键
     * @return 订单评价
     */
    @Override
    public BizServiceOrderEvaluationVO selectBizServiceOrderEvaluationById(Long id) {
        return bizServiceOrderEvaluationMapper.selectBizServiceOrderEvaluationById(id);
    }

    /**
     * 查询订单评价列表
     *
     * @param query 订单评价
     * @return 订单评价
     */
    @Override
    public List<BizServiceOrderEvaluationVO> selectBizServiceOrderEvaluationList(BizServiceOrderEvaluationQueryVO query) {
        if(query.getDateValue() != null){
            query.setStartTime(query.getDateValue()[0] + " 00:00:00");
            query.setEndTime(query.getDateValue()[1] + " 23:59:59");
        }
        return bizServiceOrderEvaluationMapper.selectBizServiceOrderEvaluationList(query);
    }

    /**
     * 新增订单评价
     *
     * @param form 订单评价
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean insertBizServiceOrderEvaluation(BizServiceOrderEvaluationFormVO form) {
        BizServiceOrderEvaluation bizServiceOrderEvaluation = new BizServiceOrderEvaluation();
        BeanUtils.copyProperties(form, bizServiceOrderEvaluation);
        bizServiceOrderEvaluation.setCreateTime(new Date());
        bizServiceOrderEvaluation.setCreateBy(SecurityUtils.getUsername());
        bizServiceOrderEvaluation.setUpdateTime(new Date());
        bizServiceOrderEvaluation.setUpdateBy(SecurityUtils.getUsername());
        return bizServiceOrderEvaluation.insert();
    }

    /**
     * 修改订单评价
     *
     * @param form 订单评价
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean updateBizServiceOrderEvaluation(BizServiceOrderEvaluationFormVO form) {
        BizServiceOrderEvaluation bizServiceOrderEvaluation = new BizServiceOrderEvaluation();
        BeanUtils.copyProperties(form, bizServiceOrderEvaluation);
        bizServiceOrderEvaluation.setUpdateTime(new Date());
        bizServiceOrderEvaluation.setUpdateBy(SecurityUtils.getUsername());
        return bizServiceOrderEvaluation.updateById();
    }

    /**
     * 批量删除订单评价
     *
     * @param ids 需要删除的订单评价主键
     * @return 结果
     */
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean deleteBizServiceOrderEvaluationByIds(Long[] ids) {
            return BizServiceOrderEvaluation.DAO.delete(Wrappers.lambdaQuery(BizServiceOrderEvaluation.class).in(BizServiceOrderEvaluation::getId, (Object[]) ids));
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public boolean changeStatus(BizStatusChangeVO vo) {
        //return BizServiceOrderEvaluation.DAO.update(Wrappers.lambdaUpdate(BizServiceOrderEvaluation.class).in(BizServiceOrderEvaluation::getId, (Object[]) vo.getIds()).set(BizServiceOrderEvaluation::getStatus, vo.getStatus()));
        return true;
    }

    @Override
    public Boolean audit(BizAuditVO auditVO) {
        LambdaUpdateWrapper<BizServiceOrderEvaluation> updateWrapper = new LambdaUpdateWrapper<BizServiceOrderEvaluation>()
                .eq(BizServiceOrderEvaluation::getId,auditVO.getId())
                .set(BizServiceOrderEvaluation::getAuditStatus,auditVO.getAuditStatus())
                .set(BizServiceOrderEvaluation::getRemark,auditVO.getRemark())
                .set(BizServiceOrderEvaluation::getUpdateBy,SecurityUtils.getUsername())
                .set(BizServiceOrderEvaluation::getUpdateTime, DateUtils.getNowDate());
        return BizServiceOrderEvaluation.DAO.update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public Boolean saveOrderEvaluation(AppServiceOrderEvaluationFormVO form) {
        BizServiceOrder bizServiceOrder = BizServiceOrder.DAO.selectById(form.getServiceOrderId());
        if(BizServiceOrder.EVALUATION_STATUS_YES.equals(bizServiceOrder.getEvaluationStatus())){
            throw new ApiException("您已经评价过该订单了");
        }
        bizServiceOrder.setEvaluationStatus(BizServiceOrder.EVALUATION_STATUS_YES);
        bizServiceOrder.setUpdateTime(DateUtils.getNowDate());
        bizServiceOrder.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserName());
        boolean update = bizServiceOrder.updateById();
        if(update){
            BizServiceOrderEvaluation evaluation = new BizServiceOrderEvaluation();
            evaluation.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            evaluation.setContent(form.getContent());
            if(StringUtils.isNotEmpty(form.getImages())){
                String[] imageArr = form.getImages().split(",");
                evaluation.setImages(JSONUtil.toJsonStr(imageArr));
            }
            evaluation.setScore(form.getScore());
            evaluation.setEvaluationTime(DateUtils.getNowDate());
            evaluation.setServiceOrderSn(bizServiceOrder.getServiceOrderSn());
            evaluation.insert();


            //计算接单陪诊用户的好评率
            //查询陪诊人员所有评价过的订单
            List<AppOrderEvaluationVO> appOrderEvaluationVOS = bizServiceOrderEvaluationMapper.selectAllEvaluationOrderByEscort(bizServiceOrder.getAcceptUserId());
            if (StringUtils.isNotNull(appOrderEvaluationVOS)){
                //将所有订单中好评的过滤出来 评分 > 3 为好评
                List<AppOrderEvaluationVO> goodList = appOrderEvaluationVOS.stream().filter(x -> x.getScore() > 3).collect(Collectors.toList());
                if(CollectionUtils.isNotEmpty(goodList)){
                    BigDecimal goodCount = BigDecimal.valueOf(goodList.size());
                    BigDecimal allCount = BigDecimal.valueOf(appOrderEvaluationVOS.size());
                    BigDecimal favorableRate = goodCount.divide(allCount, 2, BigDecimal.ROUND_CEILING).multiply(BigDecimal.valueOf(100)).setScale(1, BigDecimal.ROUND_DOWN);
                    SysUser updateUser = new SysUser();
                    updateUser.setUserId(bizServiceOrder.getAcceptUserId());
                    updateUser.setFavorableRate(favorableRate);
                    sysUserMapper.updateUser(updateUser);
                }
            }

        }
        return update;
    }

    @Override
    public List<AppOrderEvaluationVO> selectAllEvaluationOrder(String buyType, Long productId,Integer score) {
        return bizServiceOrderEvaluationMapper.selectAllEvaluationOrder(buyType,productId,score);
    }

    @Override
    public List<AppOrderEvaluationVO> selectAllEvaluationOrderByEscort(Long userId) {
        return bizServiceOrderEvaluationMapper.selectAllEvaluationOrderByEscort(userId);
    }
}
